/**
 * Created by Anarld on 2017/6/6.
 */
let variable = require('../data/variable.js');
let gameData = require('../util/gameData.js');
let userDao = require('../mysql/userDao.js');
let robotDao = require('../mysql/robotDao.js');
let timesDao = require('../mysql/timesDao.js');
let recordDao = require('../mysql/recordDao.js');
let util = require('../util/util.js');
let rpc = require('../util/rpc.js');
let msg = require('../util/msg.js');
let mem = require('../util/mem.js');

let save = module.exports;

save.setGameId = function (id, gameId) {
    let userModel = new userDao();
    userModel.inId(id, function (err, res) {
        if (res == null) {
            return false;
        }
        userModel.set('gameId', gameId);
        userModel.save(function (err1, res1) {
            let param = {};
            param.userId = userModel.data.id;
            param.status = variable.blued.statusPlaying;
            rpc.dc.send('putBluedStatus', param);
        });
    });
};
save.clearGameId = function (id, cid, uuid) {
    let userModel = new userDao();
    userModel.inId(id, function (err, res) {
        if (res == null) {
            return false;
        }
        if (res.res.gameId == 0) {
            return false;
        }
        userModel.set('gameId', 0);
        userModel.save(function (err1, res1) {
            if (cid && uuid) {
                msg.send(cid, uuid, 'gameIdClear');
            }
            let param = {};
            param.userId = userModel.data.id;
            param.status = variable.blued.statusCreating;
            rpc.dc.send('putBluedStatus', param);
        });
    });
};
save.setRobot = function (id, gameId) {
    let robotModel = new robotDao();
    robotModel.inId(id, function (err, res) {
        if (res == null) {
            return false;
        }
        robotModel.set('gameId', gameId);
        robotModel.save(function (err1, res1) {
        });
    });
};
save.clearRobot = function (id, gameId) {
    let robotModel = new robotDao();
    robotModel.inId(id, function (err, res) {
        if (res == null) {
            return false;
        }
        if (res.res.gameId == 0) {
            return false;
        }
        robotModel.set('gameId', 0);
        robotModel.save(function (err1, res1) {
        });
    });
};
save.escapee = function (id, cid, uuid, downCoin, coinType) {
    let userModel = new userDao();
    userModel.inId(id, function (err, res) {
        if (res == null) {
            return false;
        }
        let resultData = {};
        if (downCoin != 0) {
            let coin = res.res[coinType] - downCoin;
            userModel.set(coinType, coin);
            resultData[coinType] = {'now': coin, 'add': -downCoin};
        }
        userModel.set('gameId', 0);
        if (coinType != 'score') {
            let times = res.res.playTimes + 1;
            let addWins = res.res.playWins;
            userModel.set('playTimes', times);
            userModel.set('playWins', 0);
            resultData.playTimes = {'now': times, 'add': 1};
            resultData.playWins = {'now': 0, 'add': -addWins};
        }
        userModel.save(function (err1, res1) {
            if (res1 == null) {
                return false;
            }
            if (cid && uuid) {
                if (Object.keys(resultData).length > 0) {
                    msg.send(cid, uuid, 'globalUserChange', resultData);
                }
                msg.send(cid, uuid, 'gameIdClear');
                if (userModel.data.gold < gameData.d.config.loserSupportThreshold) {
                    save.loserSupport(id, cid, uuid);
                }
            }
            let param = {};
            param.userId = userModel.data.id;
            param.status = variable.blued.statusCreating;
            rpc.dc.send('putBluedStatus', param);
            save.record(id, 'play');
        });
    });
};
save.robotEscapee = function (id, downCoin, coinType) {
    let robotModel = new robotDao();
    robotModel.inId(id, function (err, res) {
        if (res == null) {
            return false;
        }
        if (downCoin != 0) {
            let coin = res.res[coinType] - downCoin;
            robotModel.set(coinType, coin);
        }
        robotModel.set('gameId', 0);
        if (coinType != 'score') {
            let times = res.res.playTimes + 1;
            robotModel.set('playTimes', times);
            robotModel.set('playWins', 0);
        }
        robotModel.save(function (err1, res1) {
        });
    });
};
save.saveResult = function (id, cid, uuid, addCoin, coinType, winner) {
    let userModel = new userDao();
    userModel.inId(id, function (err, res) {
        if (res == null) {
            return false;
        }
        let resultData = {};
        userModel.set('gameId', 0);
        if (addCoin) {
            userModel.add(coinType, addCoin);
            resultData[coinType] = {'now': userModel.data[coinType], 'add': addCoin};
        }
        if (coinType != 'score') {
            userModel.add('playTimes', 1);
            resultData.playTimes = {'now': userModel.data.playTimes, 'add': 1};
            if (winner) {
                userModel.add('playVictory', 1);
                userModel.add('playWins', 1);
                //userModel.addExp(gameData.d.config.gameWinExp);
                resultData.playVictory = {'now': userModel.data.playVictory, 'add': 1};
                resultData.playWins = {'now': userModel.data.playWins, 'add': 1};
                //resultData.exp = {'now': userModel.data.exp, 'add': gameData.d.config.gameWinExp};
            } else {
                if (res.res.playWins > 0) {
                    let playWins = res.res.playWins;
                    userModel.set('playWins', 0);
                    resultData.playWins = {'now': 0, 'add': -playWins};
                }
                //userModel.addExp(gameData.d.config.gameLostExp);
                //resultData.exp = {'now': userModel.data.exp, 'add': gameData.d.config.gameLostExp};
            }
            if (userModel.isLevelUp()) {
                resultData.lv = {'now': userModel.data.lv, 'add': userModel.levelUpReward().length};
            }
        }
        userModel.save(function (err, res) {
            if (res == null) {
                return false;
            }
            if (cid && uuid) {
                if (Object.keys(resultData).length > 0) {
                    msg.send(cid, uuid, 'globalUserChange', resultData);
                }
                msg.send(cid, uuid, 'gameIdClear');
                if (userModel.data.gold < gameData.d.config.loserSupportThreshold) {
                    save.loserSupport(id, cid, uuid);
                }
            }
            let param = {};
            param.userId = userModel.data.id;
            param.status = variable.blued.statusCreating;
            rpc.dc.send('putBluedStatus', param);
            save.record(id, 'play');
            if (winner) {
                save.record(id, 'win');
            }
            if (coinType == 'gold') {
                save.record(id, 'addGold', addCoin);
            }
            if (userModel.isLevelUp()) {
                let levelUpReward = userModel.levelUpReward();
                let levelUpRewardItemId = [];
                for (let i in levelUpReward) {
                    levelUpRewardItemId.push(gameData.d.itemAdd[levelUpReward[i]].itemId);
                    let param = {};
                    param.userId = userModel.data.id;
                    param.itemAddId = levelUpReward[i];
                    rpc.dc.send('addItem', param, function (res2) {
                        msg.send(cid, uuid, 'globalPackageChange', res2);
                    });
                }
                msg.send(cid, uuid, 'globalUserLevelUp', {
                    'oldLevel': userModel.data.lv - userModel.levelUpReward().length,
                    'newLevel': userModel.data.lv,
                    'rewardList': levelUpRewardItemId
                });
            }
        });
    });
};
save.saveAgainResult = function (id, cid, uuid, addCoin, coinType, winner) {
    let userModel = new userDao();
    userModel.inId(id, function (err, res) {
        if (res == null) {
            return false;
        }
        let resultData = {};
        if (addCoin) {
            userModel.add(coinType, addCoin);
            resultData[coinType] = {'now': userModel.data[coinType], 'add': addCoin};
        }
        userModel.save(function (err, res) {
            if (res == null) {
                return false;
            }
            if (Object.keys(resultData).length > 0) {
                msg.send(cid, uuid, 'globalUserChange', resultData);
            }
            //msg.send(cid, uuid, 'gameIdClear');
            let param = {};
            param.userId = userModel.data.id;
            param.status = variable.blued.statusCreating;
            rpc.dc.send('putBluedStatus', param);
            save.record(id, 'play');
            if (winner) {
                save.record(id, 'win');
            }
            if (userModel.isLevelUp()) {
                let levelUpReward = userModel.levelUpReward();
                let levelUpRewardItemId = [];
                for (let i in levelUpReward) {
                    levelUpRewardItemId.push(gameData.d.itemAdd[levelUpReward[i]].itemId);
                    let param = {};
                    param.userId = userModel.data.id;
                    param.itemAddId = levelUpReward[i];
                    rpc.dc.send('addItem', param, function (res2) {
                        msg.send(cid, uuid, 'globalPackageChange', res2);
                    });
                }
                msg.send(cid, uuid, 'globalUserLevelUp', {
                    'oldLevel': userModel.data.lv - userModel.levelUpReward().length,
                    'newLevel': userModel.data.lv,
                    'rewardList': levelUpRewardItemId
                });
            }
        });
    });
};

save.saveCardCost = function (id, cid, uuid, costCard) {
    let userModel = new userDao();
    userModel.inId(id, function (err, res) {
        if (res == null) {
            return false;
        }   
        let resultData = {};
        if (costCard) {
            userModel.add('card',costCard);
            resultData.card = {'now': userModel.data['card'], 'add': costCard};
        }   
        userModel.save(function (err, res) {
            if (res == null) {
                return false;
            }   
            if (Object.keys(resultData).length > 0) {
                msg.send(cid, uuid, 'globalUserChange', resultData);
            }   
        });
    });
};

save.saveArenaResult = function (id, cid, uuid, winner) {
    let userModel = new userDao();
    userModel.inId(id, function (err, res) {
        if (res == null) {
            return false;
        }
        userModel.set('gameId', 0);
        userModel.save(function (err, res) {
            if (res == null) {
                return false;
            }
            if (cid && uuid) {
                msg.send(cid, uuid, 'gameIdClear');
            }
            let param = {};
            param.userId = userModel.data.id;
            param.status = variable.blued.statusCreating;
            rpc.dc.send('putBluedStatus', param);
            //save.record(id, 'play');
            //if (winner) {
            //    save.record(id, 'win');
            //}
            //if (coinType == 'gold') {
            //    save.record(id, 'addGold', addCoin);
            //}
        });
    });
};
save.robotResult = function (id, addCoin, coinType, winner) {
    let robotModel = new robotDao();
    robotModel.inId(id, function (err, res) {
        if (res == null) {
            return false;
        }
        robotModel.set('gameId', 0);
        if (coinType == 'gold') {
            let coin = res.res.gold + addCoin;
            if (coin < res.res.goldMin) {
                coin = util.random(res.res.goldMin, res.res.goldMax, 0);
            }
            robotModel.set('gold', coin);
        }
        let times = res.res.playTimes + 1;
        robotModel.set('playTimes', times);
        if (coinType == 'gold') {
            if (winner) {
                let victory = res.res.playVictory + 1;
                let wins = res.res.playWins + 1;
                robotModel.set('playVictory', victory);
                robotModel.set('playWins', wins);
            } else if (res.res.playWins > 0) {
                let playWins = res.res.playWins;
                robotModel.set('playWins', 0);
            }
        }
        robotModel.save(function (err1, res1) {
        });
    });
};
save.loserSupport = function (id, cid, uuid) {
    let timesModel = new timesDao();
    timesModel.inId(id, function (err, res) {
        if (res == null) {
            return false;
        }
        if (gameData.d.loserSupport.length <= timesModel.data.loserSupport) {
            return false;
        }
        let lsNum = parseInt(timesModel.data.loserSupport) + 1;
        let ls = gameData.d.loserSupport[lsNum];
        if (!ls) {
            return false;
        }
        let userModel = new userDao();
        userModel.inId(id, function (err, res) {
            if (res == null) {
                return false;
            }
            let resultData = {};
            userModel.add('gold', ls.gold);
            resultData.gold = {'now': userModel.data.gold, 'add': ls.gold};
            timesModel.set('loserSupport', lsNum);
            userModel.save(function (err1, res1) {
                msg.send(cid, uuid, 'globalUserChange', resultData);
                msg.send(cid, uuid, 'globalAlert', {'text': ls.msg, 'title': null});
                timesModel.save();
            });
        });
    });
};
save.taskUpdate = function (id, cid, uuid, mode, add) {
    let param = {};
    param.userId = id;
    param.mode = mode;
    param.add = add;
    rpc.dc.send('taskUpdate', param);
    return true;
};
save.record = function (userId, type, value) {
    if (!value) {
        value = 1;
    }
    if (!mem.recordData[type]) {
        mem.recordData[type] = {};
    }
    if (!mem.recordData[type][userId]) {
        mem.recordData[type][userId] = 0;
    }
    mem.recordData[type][userId] += value;

    //let recordModel = new recordDao();
    //recordModel.set('time', new Date().Format("yyyy-MM-dd hh:mm:ss"));
    //recordModel.set('userId', userId);
    //recordModel.set('type', type);
    //if (value) {
    //    recordModel.set('value', value);
    //}
    //recordModel.save(function(){});
};